package com.chiyi.transaction;

import com.chiyi.bean.TLog;
import com.chiyi.bean.TOrder;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Random;
import java.util.UUID;

/**
 * @date 2021/5/15 13:51
 */
@Service
@Slf4j
public class OrderServiceTrans {


    @Resource
    private RocketMQTemplate rocketMQTemplate;

    // 发送事务
    public void createOrderBefore(TOrder tOrder) {
        // 事务的编号
        String txid = UUID.randomUUID().toString();
        // 发送半事务
        rocketMQTemplate.sendMessageInTransaction("tx_producer_group", "tx_topic",
                MessageBuilder.withPayload(tOrder).setHeader("txid", txid).build(), tOrder);
    }


    // 本地事务
    @Transactional
    public void createOrder(String txid, TOrder tOrder) {

        // 保存订单
        tOrder.insert();
        // 添加日志
        TLog tLog = new TLog();
        tLog.setTxId(txid);
        tLog.setContent("事务日志");
        tLog.setCreateTime(new Date());
        // 保存日志
        tLog.insert();
        int i = new Random().nextInt(10);
        log.info("{}", i);
        if (i % 3 != 0) {
            log.info("主动抛出异常");
            throw new RuntimeException();
        }
    }
}
